//
// Created by 抑~风 on 2022/11/28.
//
#include<iostream>
#include <string>
#include<fstream>
#include "regexp.h"
using namespace std;
using namespace CWJ;

string readScript5(string path){
    ifstream in (path);
    string buf ,res;
    while(in>>buf)  res += " ",res += buf;
    return res;
}

void test1(){
    string script5 = readScript5("PlayScript.txt");

    CWJLever lever;
    lever.readRule("parser_rule.txt");
    cout<<script5<<endl;
    auto tokens = lever.tokenize(script5);

    cout<<tokens.size()<<endl;
    for(auto& a : tokens){
        cout<<a.getType()<<": "<<a.getConText()<<endl;
    }
}

void showResASTNode(ResASTNode::ResASTNodePtr root,string text,unordered_set<ResASTNode::ResASTNodePtr>&st){
    if(!root)   return ;
    cout<<text<<(unsigned int )root->getNodeType()<<" " << root->getContext()<<endl;
    for(const auto & s : root->getChilds()){
        if(st.count(s) == 1)    {
            cout<<text+"    "<<(unsigned int )s->getNodeType()<<" " << s->getContext()<<endl;
            continue;
        }
        st.insert(s);
        showResASTNode(s,text+"    ",st);
    }
}

void test2(string leverFile,string grammer,string codeFile){
    GrammarLever lever(leverFile);
    auto tokens = lever.tokenize(readScript5(codeFile));
    cout<<"------------------------------------------"<<endl;
    for(int i = 0; i < tokens.size(); i++){
        const auto & a = tokens[i];
        cout<<i<<" "<<a.getType()<<" "<<a.getConText()<<endl;
    }
    GrammarParser parser(grammer);
    const auto& tree = parser.parseLL1(tokens);
    cout<<(tree == nullptr)<<endl;
    unordered_set<ResASTNode::ResASTNodePtr>st;
    showResASTNode(tree,"",st);
}

int main(){


    test2("CommonLexer.txt","PlayScript.txt","code.txt");

    cout<<"----------------- 3.8 ------------------"<<endl;

    test2("lab2_38_test_lever.txt","lab2_38_test.txt","lab2_38_code_test");

}